<template>
  <div>
    <div v-if="!isShowDetail">
      <basic-container>
        <div class="header">
          <div class="header-up">
            <div class="date-template">
              <div class="dt-item">
                <el-button size="mini" @click="delSelection">删除报告</el-button>
              </div>
            </div>
          </div>
          <div class="header-bottom">
            <cs-filter-query :options="filterQueryOptions" @change="handleChangeFilter"></cs-filter-query>
          </div>
        </div>
        <div class="feedback-table-body">
          <el-table
            :data="feedbackList"
            border
            @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="name"
              label="报告名称">
            </el-table-column>
            <el-table-column
              prop="startDate"
              label="报告时间"
              :formatter="formatterReportTime">
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="生成时间">
            </el-table-column>
            <el-table-column
              prop="createUser"
              label="创建人"
              :formatter="filterCreateUserName">
            </el-table-column>
            <el-table-column
              label="操作"
              width="180">
              <template v-slot="{row}">
                <el-tooltip class="item" effect="dark" content="查看" placement="top">
                  <i class="el-icon-view cs-button" @click="showDetail(row,false)"></i>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                  <i class="el-icon-edit cs-button" @click="showDetail(row,true)"></i>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <i class="el-icon-delete cs-button" @click="delReport(row.id)"></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.current"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="page.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </div>
      </basic-container>
    </div>
    <div v-else>
      <basic-container class="feedback-content">
        <div slot="header" class="detail-header clearfix">
          <i class="el-icon-close header-right" @click="backToTable" style="cursor: pointer"></i>
        </div>
        <el-form :model="creativeFeedbackForm" :rules="rules" ref="creativeFeedbackForm" label-width="100px">
          <el-form-item label="报告名称" prop="name">
            <el-input :readonly="!isEdit" v-model="creativeFeedbackForm.name"></el-input>
          </el-form-item>
        </el-form>
        <creative-cell :is-edit="isEdit" v-for="item in currentFeedbackDetail" :key="item.id"
                       :content="item" @remove="removeReportCell" @click-creative="previewCreative"></creative-cell>
      </basic-container>
      <div class="bottom-btn" v-show="isEdit">
        <el-button :disabled="saveLoading" size="mini" type="primary" @click="saveReport">保存</el-button>
      </div>
    </div>
    <!--素材预览-->
    <creative-card-preview v-model="mediaPreviewDialog"
                           :media-preview="currentCreative"></creative-card-preview>
  </div>
</template>

<script>
import CsFilterQuery from "@/components/CsFilterQuery/CsFilterQuery";
import CreativeCell from "@/views/creativeReport/creative-feedback/components/CreativeCell";
import {
  getCreativeFeedbackDetailById,
  getCreativeFeedbackList, removeCreativeFeedbackByIds,
  saveCreativeFeedbackGenerateReport
} from "@/api/creativeReport/creative-feedback";
import {getAllUser} from "@/api/user";
import {mapState} from "vuex";
import CreativeCardPreview from "@/components/CreativeCardPreview/CreativeCardPreview";

export default {
  name: "CreativeFeedback",
  components: {
    CsFilterQuery,
    CreativeCell,
    CreativeCardPreview
  },
  data() {
    return {
      feedbackList: [],
      isShowDetail: false,
      isEdit: false,
      currentFeedbackDetail: [],
      page: {
        current: 1,
        size: 10
      },
      total: 0,
      filterQueryObj: {},
      // 添加素材反馈表单
      creativeFeedbackForm: {
        startDate: null,
        endDate: null,
        name: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入报告名称', trigger: 'blur'},
        ]
      },
      saveLoading: false,
      // 多选
      multipleSelection: [],
      allUserList: [],
      // 预览
      mediaPreviewDialog: false,
      currentCreative: null
    }
  },
  computed: {
    ...mapState({
      offerId: state => state.user.offer
    }),
// 筛选组件配置
    filterQueryOptions() {
      return [{
        value: 'name',
        label: '报告名称'
      }, {
        value: 'createUserList',
        label: '创建人',
        queryList: this.allUserList
      }]
    }
  },
  created() {
    getAllUser({statusList: '0,1,2', isAll: true}).then(res => {
      this.allUserList = res.data.data.map(item => {
        return {
          label: item.realName,
          value: item.id
        }
      })
    });
    this.getFeedbackList()
    // 添加反馈面板
    // if (this.$route.query.add) {
    //   this.isShowDetail = true
    //   this.isEdit = true
    //   this.currentFeedbackDetail = this.$route.query.data
    //   this.creativeFeedbackForm.startDate = this.$route.query.startDate
    //   this.creativeFeedbackForm.endDate = this.$route.query.endDate
    // }
    // console.log(this.$route.query)
    // 事件总线
    this.$bus.on('addCreativeReport', params => {
      this.isShowDetail = true
      this.isEdit = true
      this.creativeFeedbackForm.id = null
      this.creativeFeedbackForm.name = ''
      this.currentFeedbackDetail = params.data
      this.creativeFeedbackForm.startDate = params.startDate
      this.creativeFeedbackForm.endDate = params.endDate
    })

  },
  mounted() {

  },
  beforeRouteLeave(to, from, next) {
    console.log('off')
    this.$bus.off('addCreativeReport')
    next()
  },
  watch: {
    offerId(val) {
      this.getFeedbackList()
    }
  },
  methods: {
    // 筛选查询
    handleChangeFilter(val) {
      this.page.current = 1
      this.filterQueryObj = val
      this.getFeedbackList()
    },
    // 显示详情
    async showDetail(row, edit) {
      this.isEdit = edit
      this.creativeFeedbackForm.name = row.name
      this.creativeFeedbackForm.endDate = row.endDate
      this.creativeFeedbackForm.startDate = row.startDate
      this.creativeFeedbackForm.id = row.id
      await this.getCreativeFeedbackDetail(row.id)
      this.isShowDetail = true
    },
    backToTable(id) {
      this.isShowDetail = false
    },
    // 翻页
    handleSizeChange(val) {
      this.page.size = val
      this.getFeedbackList()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.getFeedbackList()
    },
    // 获取反馈列表
    async getFeedbackList() {
      const {data: res} = await getCreativeFeedbackList({
        offerId: this.offerId,
        ...this.page,
        ...this.filterQueryObj
      })
      this.feedbackList = res.data.records
      this.total = res.data.total
    },
    // 获取反馈详情
    async getCreativeFeedbackDetail(id) {
      const {data: res} = await getCreativeFeedbackDetailById(id)
      this.currentFeedbackDetail = res.data
    },
    // 保存报告
    saveReport() {
      this.$refs.creativeFeedbackForm.validate(async valid => {
        if (!valid) return
        this.saveLoading = true
        if (this.currentFeedbackDetail.length === 0) return this.$message.warning('空内容，请关闭重试')
        const {data: res} = await saveCreativeFeedbackGenerateReport({
          offerId: this.offerId,
          ...this.creativeFeedbackForm,
          detailList: this.currentFeedbackDetail
        }).finally(() => {
          this.saveLoading = false
        })
        if (res.code !== 200) return
        this.$message.success('编辑成功')
        this.getFeedbackList()
        this.isShowDetail = false
      })
    },
    // 删除报告
    async delReport(ids) {
      const confirm = await this.$confirm('此操作将永久删除该报告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
      if (confirm) {
        const {data: res} = await removeCreativeFeedbackByIds(ids)
        this.page.current = 1
        await this.getFeedbackList()
      }
    },
    removeReportCell(cell) {
      this.currentFeedbackDetail = this.currentFeedbackDetail.filter(item => item !== cell)
    },
    // 多选
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val;
    },
    // 批量删除
    delSelection() {
      if (this.multipleSelection.length === 0) return
      const ids = this.multipleSelection.map(item => item.id).join(',')
      this.delReport(ids)
    },
    // 返回创建人名字
    filterCreateUserName(row, column, cellValue, index) {
      const temp = this.allUserList.find(item => item.value === cellValue)
      if (temp === undefined ){
        return  ''
      }else {
        return temp.label
      }
    },
    formatterReportTime(row) {
      return row.startDate + " 至 " + row.endDate
    },
    // 预览
    previewCreative(creative) {
      console.log(creative)
      this.currentCreative = creative
      this.mediaPreviewDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}

.header {

  .header-up {
    display: flex;
    justify-content: space-between;

    .date-template {
      .dt-item {
        display: inline-block;
        margin-bottom: 10px;
        margin-right: 10px;
      }
    }

    .yesterday {
      color: green;
    }
  }

}

.cs-button {
  cursor: pointer;
  font-size: 16px;
  color: #409EFF;
}

.feedback-table-body {
  .pagination {
    display: flex;
    justify-content: end;
    margin-top: 10px;
  }
}

.feedback-content {

}

.detail-header {
  .header-title {
    float: left;
    font-size: 16px;
    font-weight: bold;
  }

  .header-right {
    float: right;
  }
}

::v-deep .el-card__header {
  border-bottom: unset;
}

.bottom-btn {
  position: fixed;
  height: 40px;
  width: calc(100% - 220px);
  bottom: 0;
  background-color: #ffffff;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0px 2px 12px rgba(0, 0, 0, 0.1);
}
</style>
